package org.example.dolph;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONPath;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.TypeReference;
import org.example.dolph.model.PageInfo;
import org.example.dolph.model.ProjectInfo;
import org.example.dolph.model.TaskDefine;
import org.example.dolph.model.TaskDetail;
import org.example.model.DsDatasourceInfo;
import scala.Int;

import java.util.List;
import java.util.Map;

public class DolphinschedulerClient {
    private String token;

    private String url;

    public DolphinschedulerClient(String token, String url) {
        this.token = token;
        this.url = url;
    }

    public PageInfo<ProjectInfo> getProjects() {
        Map<String,String> parms = Map.of("pageNo", "1", "pageSize", "10000");
        return getPageList("/projects", ProjectInfo.class,parms);
    }

    public PageInfo<TaskDefine> getTaskDefines(String projectCode) {
        Map<String,String> parms = Map.of("pageNo", "1", "pageSize", "10000");
        return getPageList(StrUtil.format("/projects/{}/task-definition",projectCode), TaskDefine.class,parms);
    }

    public TaskDetail getTaskDetail(String projectCode, String taskCode) {
        String body = sendGetRequest(StrUtil.format("/projects/{}/task-definition/{}",projectCode,taskCode), Map.of());
        TaskDetail taskDetail = JSON.parseObject(body, TaskDetail.class);
        return taskDetail;
    }

    public DsDatasourceInfo getDsDataSource(Integer id) {
        String body = sendGetRequest(StrUtil.format("/datasources/{}",id), Map.of());
        DsDatasourceInfo taskDetail = JSON.parseObject(body, DsDatasourceInfo.class);
        return taskDetail;
    }

    private <T> PageInfo<T> getPageList(String url, Class<?> tz, Map<String,String> parms){
        String body = sendGetRequest(url,  parms);
        PageInfo<T> pageInfo = JSON.parseObject(body, new TypeReference<PageInfo<T>>(tz) {});
        return pageInfo;
    }
    JSONPath path = JSONPath.of("$.data"); // 缓存起来重复使用能提升性能
    private String sendGetRequest(String endpoint, Map<String,String> parms) {

        HttpResponse response = HttpUtil.createGet(url+endpoint)
                .header("token", token)
                .formStr(parms)
                .timeout(60*1000*10)
                .execute();

        if (response.getStatus() == 200) {

            String body = response.body();
            JSONReader parser = JSONReader.of(body);
            Object result = path.extract(parser);
            return result.toString();
        } else {
            throw new RuntimeException("Failed: HTTP error code : " + response.getStatus());
        }
    }


}
